package com.weijian.config.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weijian.dal.enums.City;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

public class CityListTypeHandler extends BaseTypeHandler<List<City>> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<City> parameter, JdbcType jdbcType) throws SQLException {
        try {
            // 将City列表转换为只包含code的列表用于存储
            List<Integer> cityCodes = parameter.stream()
                    .map(City::getCode)
                    .collect(Collectors.toList());
            
            String json = objectMapper.writeValueAsString(cityCodes);
            PGobject pgObject = new PGobject();
            pgObject.setType("jsonb");
            pgObject.setValue(json);
            ps.setObject(i, pgObject);
        } catch (JsonProcessingException e) {
            throw new SQLException("Error serializing city list to JSON", e);
        }
    }

    @Override
    public List<City> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return parseJson(json);
    }

    @Override
    public List<City> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return parseJson(json);
    }

    @Override
    public List<City> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return parseJson(json);
    }

    private List<City> parseJson(String json) throws SQLException {
        if (json == null || json.isEmpty()) {
            return null;
        }
        try {
            List<Integer> cityCodes = objectMapper.readValue(json, new TypeReference<List<Integer>>() {});
            return cityCodes.stream()
                    .map(City::fromCode)
                    .collect(Collectors.toList());
        } catch (JsonProcessingException e) {
            throw new SQLException("Error deserializing JSON to city list: " + json, e);
        }
    }
}